<template>
	<div class="home-container">
		<!-- 顶部栏 -->
		<van-nav-bar>
			<!-- 左侧 -->
			<template #left>
				<div class="logo"></div>
			</template>
			<!-- 右侧 -->
			<template #right>
				<van-button @click="$router.push('/search')" round icon="search"
					>搜索</van-button
				>
			</template>
		</van-nav-bar>

		<!-- 频道栏 -->
		<!-- vant提供的v-model获取频道下标 -->
		<van-tabs v-model="active">
			<!-- 频道 -->
			<van-tab v-for="item in channelsList" :key="item.id" :title="item.name">
				<!-- 文章栏 -->
				<article-list :channel_id="item.id" />
			</van-tab>
			<!-- 图标 -->
			<div class="icon-box">
				<van-icon @click="$refs.channelEdit.show = true" name="wap-nav" />
			</div>
		</van-tabs>

		<!-- 频道管理 -->
		<!-- 优化 v-model有语法糖 -->
		<!-- 会生成:value="数据"
      @input="数据 = $event" -->
		<!-- 注意:必须使用子组件value 和input -->
		<channel-edit
			ref="channelEdit"
			:myList="channelsList"
			:allList="allChannelsList"
			v-model="active"
		/>
	</div>
</template>

<script>
import { userChannelsAPI, allChannelsAPI } from "@/api/channels";
import ArticleList from "./ArticleList.vue";
import ChannelEdit from "./ChannelEdit.vue";

export default {
	components: { ArticleList, ChannelEdit },
	data() {
		return {
			channelsList: [],
			allChannelsList: [],
			active: 0,
		};
	},
	created() {
		// 获取频道
		this.judgeChannels();
		// 获取全部频道
		this.allChannels();
	},
	methods: {
		// 获取用户频道
		// 可以传入token（不强制）
		// 传入返回用户频道，否则返回默认频道
		async getChannels() {
			const res = await userChannelsAPI();
			this.channelsList = res.data.channels;
			// console.log(res);
		},
		async allChannels() {
			const res = await allChannelsAPI();
			this.allChannelsList = res.data.channels;
		},
		// 判断是否登录，获取用户频道或者默认频道
		judgeChannels() {
			const localChannels = JSON.parse(localStorage.getItem("channels"));
			// 登录了，或者本地没有数据则请求服务器
			if (this.$store.state.tokenObj.token || !localChannels) {
				this.getChannels();
			} else {
				// 没登录以及本地有频道数据，则从本地获取
				this.channelsList = JSON.parse(localStorage.getItem("channels"));
			}
		},
	},
};
</script>

<style scoped lang='less'>
.van-nav-bar {
	.logo {
		width: 120px;
		height: 46px;
		background: url(@/assets/logo.png) no-repeat center / contain;
	}
	.van-button {
		width: 100px;
		height: 30px;
		background-color: rgba(255, 255, 255, 0.2);
		border: none;
		color: #fff;
		.van-icon-search {
			color: #fff;
		}
	}
}

.van-tabs {
	position: relative;
	.icon-box {
		position: absolute;
		right: 0;
		top: 3px;
		font-size: 30px;
	}
	::v-deep .van-tabs__wrap {
		position: absolute;
		left: 0;
		right: 30px;
	}
}
</style>